package com.example;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
@description:版本1：使用线程池处理批量任务
@ClassName SimpleBatchTaskUtils
@author chen
@create 2025-06-06 17:18
@Version 1.0
*/
public class SimpleBatchTaskUtils
{
    public static void main(String[] args)
    {
        batchTaskTest();
    }


    public static void batchTaskTest()
    {
        long startTime = System.currentTimeMillis();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++)
        {
            list.add("短信-" + i);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(10);


        CountDownLatch countDownLatch = new CountDownLatch(list.size());

        for (String task : list)
        {
            executorService.execute(() ->
            {
                try
                {
                    // 交给线程池处理任务
                    disposeTask(task);
                } finally
                {
                    // 处理完成后调用 countDownLatch.countDown()
                    countDownLatch.countDown();
                }
            });
        }
        try
        {
            // 阻塞当前线程池
            countDownLatch.await();
        }
        catch (InterruptedException e)
        {
            throw new RuntimeException(e);
        }
        System.out.println("任务处理完毕,耗时(ms):" + (System.currentTimeMillis() - startTime));
        executorService.shutdown();
    }

    public static void disposeTask(String task)
    {
        System.out.printf("【%s】发送成功%n", task);
    }

}
